package com.example.mydy.utils;

import com.example.mydy.model.Advertisement;
import com.example.mydy.model.Announcement;
import com.example.mydy.model.Project;
import com.example.mydy.model.ProjectUnlockStatus;
import com.example.mydy.model.RewardTask;
import com.example.mydy.model.Task;
import com.example.mydy.model.UserData;
import com.example.mydy.model.UserInfo;
import com.example.mydy.model.UserRewardPrivilege;
import com.example.mydy.model.WithdrawalRecord;
import com.example.mydy.model.IncomeRecord;
import com.example.mydy.model.TaskRecord;
import com.example.mydy.model.DownlineIncomeRecord;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import android.util.Log;
import android.content.Context;
import java.text.SimpleDateFormat;
import java.util.Locale;

/**
 * 模拟数据管理器，提供离线模式下的数据
 */
public class MockDataManager {

    private static final String TAG = "MockDataManager";
    private static final Random random = new Random();
    
    // 单例实例
    private static MockDataManager instance;
    
    // 全局任务奖励设置
    private static double DEFAULT_TASK_REWARD = 5.0; // 默认任务奖励金额
    
    // 任务奖励的默认分成比例
    private static double DEFAULT_LEVEL1_RATIO = 50.0; // 一级分成：50%
    private static double DEFAULT_LEVEL2_RATIO = 25.0; // 二级分成：25%
    private static double DEFAULT_LEVEL3_RATIO = 10.0; // 三级分成：10%
    
    // 存储用户数据的集合
    private static final Map<String, UserData> userDataMap = new HashMap<>();
    private static final Map<String, String> userRoles = new HashMap<>();
    
    // 测试用户常量
    public static final String DEFAULT_TEST_USER = "user1";
    public static final String DEFAULT_TEST_ADMIN = "admin";
    
    // 当前登录用户
    private static String currentUsername = null;
    
    // 存储任务数据的集合
    private static final List<Task> pendingTasks = new ArrayList<>();
    private static final List<RewardTask> rewardTasks = new ArrayList<>();
    private static final List<Advertisement> advertisements = new ArrayList<>();
    private static final List<Announcement> announcements = new ArrayList<>();
    private static List<Project> projects = new ArrayList<>();
    
    // 存储用户特权奖励的集合
    private static final List<UserRewardPrivilege> userRewardPrivileges = new ArrayList<>();
    
    // 存储用户解锁项目的状态信息
    private static final List<ProjectUnlockStatus> projectUnlockStatuses = new ArrayList<>();
    
    // 存储提现记录的集合
    private static final List<WithdrawalRecord> withdrawalRecords = new ArrayList<>();
    private static int nextWithdrawalId = 1;  // 用于生成唯一的提现记录ID
    
    // 私有构造函数，防止外部实例化
    private MockDataManager() {
        // 私有构造函数
    }
    
    /**
     * 获取MockDataManager单例实例
     */
    public static synchronized MockDataManager getInstance() {
        if (instance == null) {
            instance = new MockDataManager();
        }
        return instance;
    }
    
    /**
     * 获取MockDataManager单例实例（带Context参数的重载）
     */
    public static synchronized MockDataManager getInstance(Context context) {
        if (instance == null) {
            instance = new MockDataManager();
        }
        return instance;
    }
    
    // 设置当前用户
    public void setCurrentUser(String username) {
        currentUsername = username;
    }
    
    // 获取当前用户名
    public String getCurrentUsername() {
        return currentUsername;
    }
    
    /**
     * 获取当前用户信息
     */
    public UserInfo getCurrentUser() {
        if (currentUsername == null) {
            Log.e(TAG, "getCurrentUser: 当前用户名为空");
            return null;
        }
        
        Log.d(TAG, "getCurrentUser: 当前登录用户名=" + currentUsername);
        
        // 如果是test_user，使用默认测试用户的数据
        String username = currentUsername;
        if ("test_user".equals(username)) {
            username = DEFAULT_TEST_USER;
            Log.d(TAG, "getCurrentUser: 使用默认测试用户 " + DEFAULT_TEST_USER + " 替代 test_user");
        }
        
        // 检查用户是否存在于userDataMap中
        if (!userDataMap.containsKey(username)) {
            Log.e(TAG, "getCurrentUser: 用户 " + username + " 不存在于userDataMap中");
            
            // 查看当前userDataMap中的用户
            StringBuilder userList = new StringBuilder("当前存在的用户: ");
            for (String user : userDataMap.keySet()) {
                userList.append(user).append(", ");
            }
            Log.d(TAG, userList.toString());
            
            // 如果当前用户不存在，使用默认测试用户
            if (userDataMap.containsKey(DEFAULT_TEST_USER)) {
                username = DEFAULT_TEST_USER;
                Log.d(TAG, "getCurrentUser: 找不到用户 " + currentUsername + "，使用默认测试用户 " + DEFAULT_TEST_USER);
            } else {
                return null;
            }
        }
        
        UserData userData = userDataMap.get(username);
        if (userData == null) {
            Log.e(TAG, "getCurrentUser: 未找到用户数据: " + username);
            return null;
        }
        
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(currentUsername); // 保持原始用户名
        userInfo.setNickname(userData.getNickname());
        userInfo.setBalance(String.valueOf(userData.getBalance()));
        userInfo.setId(1); // 使用固定ID
        userInfo.setEmail(userData.getUsername() + "@example.com");
        userInfo.setLevel("普通"); // 使用字符串类型的等级
        userInfo.setPoints(0); // 设置默认积分
        userInfo.setStatus("normal"); // 设置默认状态
        
        // 设置用户头像URL
        userInfo.setAvatarUrl(userData.getAvatarUrl());
        
        Log.d(TAG, "getCurrentUser: 成功获取用户信息: " + userInfo.getUsername() + ", 余额=" + userInfo.getBalance());
        
        return userInfo;
    }
    
    /**
     * 生成测试数据
     */
    public void generateMockData() {
        // 测试数据已在静态初始化块中生成
        // 这里可以添加额外的测试数据生成
        Log.d(TAG, "生成测试数据");
    }
    
    /**
     * 获取用户的今日总收益
     * @param username 用户名
     * @return 今日总收益
     */
    public double getTodayIncome(String username) {
        double taskIncome = getTodayTaskIncome(username);
        double rewardIncome = getTodayRewardIncome(username);
        double downlineIncome = getTodayDownlineIncome(username);
        return taskIncome + rewardIncome + downlineIncome;
    }
    
    /**
     * 获取用户今日来自任务的收益
     * @param username 用户名
     * @return 今日任务收益
     */
    public double getTodayTaskIncome(String username) {
        // 模拟数据 - 实际应用中应从数据库查询
        return 25.0;
    }
    
    /**
     * 获取用户今日来自悬赏的收益
     * @param username 用户名
     * @return 今日悬赏收益
     */
    public double getTodayRewardIncome(String username) {
        // 模拟数据 - 实际应用中应从数据库查询
        return 18.0;
    }
    
    /**
     * 获取用户今日来自下级的收益
     * @param username 用户名
     * @return 今日下级收益
     */
    public double getTodayDownlineIncome(String username) {
        // 获取所有下级收益记录
        List<DownlineIncomeRecord> records = getUserDownlineIncomeRecords(username);
        
        // 只计算今天的收益
        double todayIncome = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        String today = sdf.format(new Date());
        
        for (DownlineIncomeRecord record : records) {
            // 只统计今天创建的记录
            if (record.getCreateTime().startsWith(today)) {
                todayIncome += record.getAmount();
            }
        }
        
        return todayIncome;
    }
    
    /**
     * 获取用户的已完成且审核通过的任务数量
     * @param username 用户名
     * @return 已完成任务数量
     */
    public int getCompletedTaskCount(String username) {
        // 模拟数据 - 实际应用中应从数据库查询只统计状态为"已通过"的任务
        return 8;
    }
    
    /**
     * 获取用户的总下级收益（原邀请奖励）
     * @param username 用户名
     * @return 下级总收益
     */
    public double getTotalDownlineIncome(String username) {
        // 模拟数据 - 实际应用中应从数据库查询所有下级贡献的收益总和
        return 128.50;
    }
    
    /**
     * 获取用户的下级用户列表
     * @param username 用户名
     * @return 下级用户列表
     */
    public List<UserInfo> getDownlineUsers(String username) {
        // 模拟数据 - 实际应用中应从数据库查询
        List<UserInfo> downlineUsers = new ArrayList<>();
        
        // 添加一些模拟的下级用户
        for (int i = 0; i < 5; i++) {
            UserInfo user = new UserInfo();
            user.setId(1000 + i);
            user.setUsername("user" + (1000 + i));
            user.setNickname("下级用户" + (i + 1));
            user.setLevel(i < 2 ? "一级" : "二级");
            downlineUsers.add(user);
        }
        
        return downlineUsers;
    }
    
    /**
     * 获取用户的收益记录
     * @param username 用户名
     * @return 收益记录列表
     */
    public List<IncomeRecord> getUserIncomeRecords(String username) {
        // 模拟数据 - 实际应用中应从数据库查询
        List<IncomeRecord> records = new ArrayList<>();
        
        // 添加一些模拟的收益记录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date now = new Date();
        
        // 任务收益记录
        IncomeRecord taskRecord1 = new IncomeRecord();
        taskRecord1.setId(1);
        taskRecord1.setUsername(username);
        taskRecord1.setAmount(10.0);
        taskRecord1.setType(IncomeRecord.TYPE_TASK);
        taskRecord1.setDescription("完成任务：APP测试反馈");
        taskRecord1.setCreateTime(sdf.format(new Date(now.getTime() - 3600000))); // 1小时前
        records.add(taskRecord1);
        
        IncomeRecord taskRecord2 = new IncomeRecord();
        taskRecord2.setId(2);
        taskRecord2.setUsername(username);
        taskRecord2.setAmount(15.0);
        taskRecord2.setType(IncomeRecord.TYPE_TASK);
        taskRecord2.setDescription("完成任务：产品问卷调查");
        taskRecord2.setCreateTime(sdf.format(new Date(now.getTime() - 7200000))); // 2小时前
        records.add(taskRecord2);
        
        // 悬赏收益记录
        IncomeRecord rewardRecord = new IncomeRecord();
        rewardRecord.setId(3);
        rewardRecord.setUsername(username);
        rewardRecord.setAmount(18.0);
        rewardRecord.setType(IncomeRecord.TYPE_REWARD);
        rewardRecord.setDescription("完成悬赏：网站漏洞检测");
        rewardRecord.setCreateTime(sdf.format(new Date(now.getTime() - 10800000))); // 3小时前
        records.add(rewardRecord);
        
        // 下级收益记录
        IncomeRecord downlineRecord1 = new IncomeRecord();
        downlineRecord1.setId(4);
        downlineRecord1.setUsername(username);
        downlineRecord1.setAmount(5.0);
        downlineRecord1.setType(IncomeRecord.TYPE_DOWNLINE);
        downlineRecord1.setDescription("下级user1001完成任务");
        downlineRecord1.setCreateTime(sdf.format(new Date(now.getTime() - 14400000))); // 4小时前
        records.add(downlineRecord1);
        
        IncomeRecord downlineRecord2 = new IncomeRecord();
        downlineRecord2.setId(5);
        downlineRecord2.setUsername(username);
        downlineRecord2.setAmount(4.5);
        downlineRecord2.setType(IncomeRecord.TYPE_DOWNLINE);
        downlineRecord2.setDescription("下级user1002完成任务");
        downlineRecord2.setCreateTime(sdf.format(new Date(now.getTime() - 18000000))); // 5小时前
        records.add(downlineRecord2);
        
        return records;
    }
    
    /**
     * 获取用户已完成的任务记录
     * @param username 用户名
     * @return 任务记录列表
     */
    public List<TaskRecord> getUserCompletedTasks(String username) {
        // 模拟数据 - 实际应用中应从数据库查询
        List<TaskRecord> taskRecords = new ArrayList<>();
        
        // 添加一些模拟的任务记录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date now = new Date();
        
        TaskRecord task1 = new TaskRecord();
        task1.setId(1);
        task1.setUsername(username);
        task1.setTaskName("APP测试反馈");
        task1.setTaskDescription("测试新版APP功能并提供详细反馈");
        task1.setReward(10.0);
        task1.setStatus(TaskRecord.STATUS_APPROVED);
        task1.setCompletionTime(sdf.format(new Date(now.getTime() - 3600000))); // 1小时前
        task1.setApprovalTime(sdf.format(new Date(now.getTime() - 1800000))); // 30分钟前
        taskRecords.add(task1);
        
        TaskRecord task2 = new TaskRecord();
        task2.setId(2);
        task2.setUsername(username);
        task2.setTaskName("产品问卷调查");
        task2.setTaskDescription("完成产品使用体验问卷调查");
        task2.setReward(15.0);
        task2.setStatus(TaskRecord.STATUS_APPROVED);
        task2.setCompletionTime(sdf.format(new Date(now.getTime() - 7200000))); // 2小时前
        task2.setApprovalTime(sdf.format(new Date(now.getTime() - 5400000))); // 1.5小时前
        taskRecords.add(task2);
        
        TaskRecord task3 = new TaskRecord();
        task3.setId(3);
        task3.setUsername(username);
        task3.setTaskName("网站漏洞检测");
        task3.setTaskDescription("检测并报告网站安全漏洞");
        task3.setReward(18.0);
        task3.setStatus(TaskRecord.STATUS_APPROVED);
        task3.setCompletionTime(sdf.format(new Date(now.getTime() - 10800000))); // 3小时前
        task3.setApprovalTime(sdf.format(new Date(now.getTime() - 9000000))); // 2.5小时前
        taskRecords.add(task3);
        
        return taskRecords;
    }
    
    /**
     * 获取用户的下级收益记录
     * @param username 用户名
     * @return 下级收益记录列表
     */
    public List<DownlineIncomeRecord> getUserDownlineIncomeRecords(String username) {
        // 模拟数据 - 实际应用中应从数据库查询
        List<DownlineIncomeRecord> records = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String today = sdf.format(new Date());
        
        // 添加一级下线收益记录
        DownlineIncomeRecord level1Record1 = new DownlineIncomeRecord();
        level1Record1.setId(1);
        level1Record1.setUsername(username);
        level1Record1.setDownlineUsername("user_level1_1");
        level1Record1.setDownlineNickname("一级下线用户1");
        level1Record1.setLevel(1); // 一级下线
        level1Record1.setAmount(10.5); // 一级分成收益
        level1Record1.setTaskName("完成任务测试A");
        level1Record1.setCreateTime(today);
        records.add(level1Record1);
        
        DownlineIncomeRecord level1Record2 = new DownlineIncomeRecord();
        level1Record2.setId(2);
        level1Record2.setUsername(username);
        level1Record2.setDownlineUsername("user_level1_2");
        level1Record2.setDownlineNickname("一级下线用户2");
        level1Record2.setLevel(1); // 一级下线
        level1Record2.setAmount(8.0); // 一级分成收益
        level1Record2.setTaskName("完成任务测试B");
        level1Record2.setCreateTime(today);
        records.add(level1Record2);
        
        // 添加二级下线收益记录
        DownlineIncomeRecord level2Record1 = new DownlineIncomeRecord();
        level2Record1.setId(3);
        level2Record1.setUsername(username);
        level2Record1.setDownlineUsername("user_level2_1");
        level2Record1.setDownlineNickname("二级下线用户1");
        level2Record1.setLevel(2); // 二级下线
        level2Record1.setAmount(5.25); // 二级分成收益
        level2Record1.setTaskName("完成任务测试C");
        level2Record1.setCreateTime(today);
        records.add(level2Record1);
        
        // 添加三级下线收益记录
        DownlineIncomeRecord level3Record1 = new DownlineIncomeRecord();
        level3Record1.setId(4);
        level3Record1.setUsername(username);
        level3Record1.setDownlineUsername("user_level3_1");
        level3Record1.setDownlineNickname("三级下线用户1");
        level3Record1.setLevel(3); // 三级下线
        level3Record1.setAmount(2.1); // 三级分成收益
        level3Record1.setTaskName("完成任务测试D");
        level3Record1.setCreateTime(today);
        records.add(level3Record1);
        
        return records;
    }
    
    /**
     * 获取公告列表
     */
    public List<Announcement> getAnnouncements(int limit) {
        List<Announcement> result = new ArrayList<>(announcements);
        if (result.size() > limit) {
            result = result.subList(0, limit);
        }
        return result;
    }
    
    /**
     * 获取热门悬赏列表
     */
    public List<RewardTask> getHotRewards(int limit) {
        List<RewardTask> result = new ArrayList<>(rewardTasks);
        if (result.size() > limit) {
            result = result.subList(0, limit);
        }
        return result;
    }
    
    // 判断当前用户是否是管理员
    public boolean isCurrentUserAdmin() {
        return currentUsername != null && DEFAULT_TEST_ADMIN.equals(currentUsername);
    }
    
    /**
     * 获取用户的邀请码
     * @param username 用户名
     * @return 用户的邀请码，如果不存在则返回生成的邀请码
     */
    public String getInviteCode(String username) {
        // 使用用户名的hashCode创建一个唯一的邀请码
        UserData userData = userDataMap.get(username);
        if (userData != null && userData.getInviteCode() != null && !userData.getInviteCode().isEmpty()) {
            return userData.getInviteCode();
        }
        
        // 如果用户数据不存在或邀请码为空，则生成一个新的邀请码
        String inviteCode = generateInviteCode(username);
        
        // 如果用户数据存在，更新用户的邀请码
        if (userData != null) {
            userData.setInviteCode(inviteCode);
            userDataMap.put(username, userData);
        }
        
        return inviteCode;
    }
    
    /**
     * 生成邀请码
     * @param seed 种子字符串
     * @return 生成的6位字母数字邀请码
     */
    private String generateInviteCode(String seed) {
        // 确保即使相同用户名也会生成固定的邀请码
        Random random = new Random(seed.hashCode());
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(chars.length());
            sb.append(chars.charAt(index));
        }
        return sb.toString();
    }
    
    public void logout() {
        currentUsername = null;
    }
    
    // 静态初始化块，初始化一些测试数据
    static {
        // 初始化用户数据
        UserData userData1 = new UserData();
        userData1.setUsername("user1");
        userData1.setNickname("测试用户1");
        userData1.setBalance(100.0);
        userData1.setTodayInvites(5);
        userData1.setTodayTaskReward(20.0);
        userData1.setTodaySubTaskReward(10.0);
        
        UserData userData2 = new UserData();
        userData2.setUsername("user2");
        userData2.setNickname("测试用户2");
        userData2.setBalance(200.0);
        userData2.setTodayInvites(3);
        userData2.setTodayTaskReward(15.0);
        userData2.setTodaySubTaskReward(5.0);
        userData2.setInviter("user1");  // user2由user1邀请
        
        UserData userData3 = new UserData();
        userData3.setUsername("user3");
        userData3.setNickname("测试用户3");
        userData3.setBalance(150.0);
        userData3.setTodayInvites(2);
        userData3.setTodayTaskReward(12.0);
        userData3.setTodaySubTaskReward(8.0);
        userData3.setInviter("user2");  // user3由user2邀请
        
        UserData userData4 = new UserData();
        userData4.setUsername("user4");
        userData4.setNickname("测试用户4");
        userData4.setBalance(50.0);
        userData4.setTodayInvites(1);
        userData4.setTodayTaskReward(5.0);
        userData4.setTodaySubTaskReward(2.0);
        userData4.setInviter("user3");  // user4由user3邀请
        
        UserData adminData = new UserData();
        adminData.setUsername("admin");
        adminData.setNickname("管理员");
        adminData.setBalance(1000.0);
        adminData.setTodayInvites(0);
        adminData.setTodayTaskReward(0.0);
        adminData.setTodaySubTaskReward(0.0);
        
        userDataMap.put(userData1.getUsername(), userData1);
        userDataMap.put(userData2.getUsername(), userData2);
        userDataMap.put(userData3.getUsername(), userData3);
        userDataMap.put(userData4.getUsername(), userData4);
        userDataMap.put(adminData.getUsername(), adminData);
        
        userRoles.put("user1", "user");
        userRoles.put("user2", "user");
        userRoles.put("user3", "user");
        userRoles.put("user4", "user");
        userRoles.put("admin", "admin");
        
        // 初始化奖励任务数据
        RewardTask rewardTask1 = new RewardTask();
        rewardTask1.setId(1);
        rewardTask1.setTitle("测试奖励任务1");
        rewardTask1.setDescription("这是测试奖励任务1的详细描述");
        rewardTask1.setReward(10.0);
        rewardTask1.setTotalOrders(5);
        rewardTask1.setRemainingOrders(3);
        rewardTask1.setTaken(false);
        
        RewardTask rewardTask2 = new RewardTask();
        rewardTask2.setId(2);
        rewardTask2.setTitle("测试奖励任务2");
        rewardTask2.setDescription("这是测试奖励任务2的详细描述");
        rewardTask2.setReward(20.0);
        rewardTask2.setTotalOrders(10);
        rewardTask2.setRemainingOrders(5);
        rewardTask2.setTaken(false);
        
        rewardTasks.add(rewardTask1);
        rewardTasks.add(rewardTask2);
        
        // 初始化广告数据
        Advertisement ad1 = new Advertisement();
        ad1.setId(1);
        ad1.setTitle("促销活动");
        ad1.setContent("限时优惠，全场商品8折起，活动截止到本月底！");
        ad1.setImageUrl("https://example.com/ads/promo.jpg");
        ad1.setLink("https://example.com/promotion");
        ad1.setCreatedAt(new Date());
        
        Advertisement ad2 = new Advertisement();
        ad2.setId(2);
        ad2.setTitle("新品上市");
        ad2.setContent("全新产品系列已经上线，抢先体验新功能！");
        ad2.setImageUrl("https://example.com/ads/new_product.jpg");
        ad2.setLink("https://example.com/new_products");
        ad2.setCreatedAt(new Date());
        
        Advertisement ad3 = new Advertisement();
        ad3.setId(3);
        ad3.setTitle("会员专享");
        ad3.setContent("注册会员即可享受专属折扣和服务，会员日特惠更多！");
        ad3.setImageUrl("https://example.com/ads/member.jpg");
        ad3.setLink("https://example.com/membership");
        ad3.setCreatedAt(new Date());
        
        advertisements.add(ad1);
        advertisements.add(ad2);
        advertisements.add(ad3);
        
        // 初始化公告数据
        Announcement announcement1 = new Announcement();
        announcement1.setId(1);
        announcement1.setTitle("系统更新通知");
        announcement1.setContent("系统将于本周日凌晨2点进行维护更新，预计需要2小时。");
        announcement1.setCreatedAt(new Date());
        
        Announcement announcement2 = new Announcement();
        announcement2.setId(2);
        announcement2.setTitle("新功能上线");
        announcement2.setContent("我们新增了任务管理和奖励系统，欢迎尝试并提供反馈。");
        announcement2.setCreatedAt(new Date());
        
        announcements.add(announcement1);
        announcements.add(announcement2);
        
        // 初始化一些示例项目数据
        Date now = new Date();
        
        Project project1 = new Project(1, "网站前端开发", "需要开发一个响应式企业网站前端，要求使用HTML5、CSS3和JavaScript，兼容主流浏览器。", 
                2000.0, "https://example.com/images/project1.jpg", now, Project.STATUS_ACTIVE, 2);
        
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -2);
        Date twoDaysAgo = calendar.getTime();
        
        Project project2 = new Project(2, "Android应用开发", "开发一款社交媒体Android应用，包含用户注册、登录、发帖、评论等基本功能。", 
                5000.0, "https://example.com/images/project2.jpg", twoDaysAgo, Project.STATUS_ACTIVE, 3);
        
        calendar.add(Calendar.DAY_OF_MONTH, -5);
        Date weekAgo = calendar.getTime();
        
        Project project3 = new Project(3, "Logo设计", "为一家科技初创公司设计现代简约风格的Logo，需提供AI源文件和多种格式导出文件。", 
                800.0, "https://example.com/images/project3.jpg", weekAgo, Project.STATUS_ACTIVE, 4);
        
        projects.add(project1);
        projects.add(project2);
        projects.add(project3);
        
        // 初始化一些待审核任务
        for (int i = 1; i <= 5; i++) {
            Task task = new Task();
            task.setId(i);
            task.setTitle("待审核任务 " + i);
            task.setDescription("这是待审核任务 " + i + " 的描述信息，用户已提交内容等待管理员审核。");
            task.setReward(i * 10.0);
            task.setStatus(Task.STATUS_PENDING);
            task.setCreatedAt("2023-10-" + (i < 10 ? "0" + i : i));
            task.setUserId(i + 1);
            
            // 为部分任务添加图片
            if (i % 2 == 0) {
                task.setImageUrl("https://via.placeholder.com/300x200?text=Task" + i);
            }
            
            // 分配给不同用户
            switch (i) {
                case 1:
                    task.setUsername("user1"); // 无推荐人的用户
                    break;
                case 2:
                    task.setUsername("user2"); // 有1级推荐关系的用户
                    break;
                case 3:
                    task.setUsername("user3"); // 有1级和2级推荐关系的用户
                    break;
                case 4:
                    task.setUsername("user4"); // 有1、2、3级完整推荐链的用户
                    break;
                default:
                    task.setUsername("admin"); // 管理员
                    break;
            }
            
            pendingTasks.add(task);
        }
        
        // 初始化一些用户特权奖励数据
        java.util.Calendar privilegeCalendar = java.util.Calendar.getInstance();
        java.util.Date currentDate = privilegeCalendar.getTime();
        
        // 未来一个月的结束日期
        privilegeCalendar.add(java.util.Calendar.MONTH, 1);
        java.util.Date oneMonthLater = privilegeCalendar.getTime();
        
        // 已经过期的日期（过去一个月）
        privilegeCalendar.add(java.util.Calendar.MONTH, -2);
        java.util.Date oneMonthAgo = privilegeCalendar.getTime();
        
        // 添加测试数据
        UserRewardPrivilege privilege1 = new UserRewardPrivilege(
            1, "user1", 60.0, 30.0, 15.0, 3.0, currentDate, oneMonthLater, "特级推广员"
        );
        
        UserRewardPrivilege privilege2 = new UserRewardPrivilege(
            2, "user2", 55.0, 28.0, 12.0, 2.5, oneMonthAgo, currentDate, "已过期特权"
        );
        
        UserRewardPrivilege privilege3 = new UserRewardPrivilege(
            3, "admin", 70.0, 35.0, 18.0, 5.0, currentDate, null, "管理员特权（永久）"
        );
        
        userRewardPrivileges.add(privilege1);
        userRewardPrivileges.add(privilege2);
        userRewardPrivileges.add(privilege3);
    }

    // 获取模拟的管理员用户信息
    public static UserInfo getMockAdminUser() {
        UserInfo adminUserInfo = new UserInfo();
        adminUserInfo.setUsername("admin");
        adminUserInfo.setPassword("admin123");
        adminUserInfo.setNickname("管理员");
        adminUserInfo.setAdmin(true);
        return adminUserInfo;
    }

    // 获取等待审核的任务列表
    public static List<Task> getPendingTasks() {
        return new ArrayList<>(pendingTasks);
    }
    
    /**
     * 获取任务奖励
     * @return 当前设置的任务奖励金额
     */
    public static double getTaskReward() {
        return DEFAULT_TASK_REWARD;
    }
    
    /**
     * 设置任务奖励金额
     * @param reward 新的任务奖励金额
     */
    public static void setTaskReward(double reward) {
        if (reward > 0) {
            DEFAULT_TASK_REWARD = reward;
            Log.d(TAG, "设置任务奖励金额: " + reward);
        }
    }

    /**
     * 获取默认一级分成比例
     * @return 默认一级分成比例
     */
    public static double getDefaultLevel1Ratio() {
        return DEFAULT_LEVEL1_RATIO;
    }

    /**
     * 设置默认一级分成比例
     * @param ratio 新的默认一级分成比例
     */
    public static void setDefaultLevel1Ratio(double ratio) {
        if (ratio >= 0 && ratio <= 100) {
            DEFAULT_LEVEL1_RATIO = ratio;
        }
    }

    /**
     * 获取默认二级分成比例
     * @return 默认二级分成比例
     */
    public static double getDefaultLevel2Ratio() {
        return DEFAULT_LEVEL2_RATIO;
    }

    /**
     * 设置默认二级分成比例
     * @param ratio 新的默认二级分成比例
     */
    public static void setDefaultLevel2Ratio(double ratio) {
        if (ratio >= 0 && ratio <= 100) {
            DEFAULT_LEVEL2_RATIO = ratio;
        }
    }

    /**
     * 获取默认三级分成比例
     * @return 默认三级分成比例
     */
    public static double getDefaultLevel3Ratio() {
        return DEFAULT_LEVEL3_RATIO;
    }

    /**
     * 设置默认三级分成比例
     * @param ratio 新的默认三级分成比例
     */
    public static void setDefaultLevel3Ratio(double ratio) {
        if (ratio >= 0 && ratio <= 100) {
            DEFAULT_LEVEL3_RATIO = ratio;
        }
    }
    
    /**
     * 提交任务到待审核列表
     * @param task 任务对象
     * @return 是否提交成功
     */
    public boolean submitTask(Task task) {
        try {
            // 为任务分配ID
            int maxId = 0;
            for (Task t : pendingTasks) {
                if (t.getId() > maxId) {
                    maxId = t.getId();
                }
            }
            task.setId(maxId + 1);
            
            // 设置默认奖励金额
            task.setReward(DEFAULT_TASK_REWARD);
            
            // 添加到待审核任务列表
            pendingTasks.add(task);
            
            Log.d(TAG, "成功提交任务：ID=" + task.getId() + ", 标题=" + task.getTitle() + 
                  ", 用户=" + task.getUsername() + ", 奖励=" + DEFAULT_TASK_REWARD);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "提交任务时发生异常", e);
            return false;
        }
    }
    
    // 根据任务ID获取待审核任务详情
    public static Task getTaskById(int taskId) {
        for (Task task : pendingTasks) {
            if (task.getId() == taskId) {
                return task;
            }
        }
        return null;
    }
    
    // 审核通过任务，更新版本
    public static boolean approveTask(int taskId) {
        Task task = getTaskById(taskId);
        if (task == null) {
            Log.e(TAG, "审核任务失败: 找不到任务ID " + taskId);
            return false;
        }
        
        // 更新任务状态
        task.setStatus(Task.STATUS_APPROVED);
        String username = task.getUsername();
        
        // 获取任务奖励金额
        double taskReward = task.getReward();
        
        // 查找用户
        UserData userData = getInstance().getUserData(username);
        if (userData == null) {
            Log.e(TAG, "审核任务失败: 找不到用户 " + username);
            return false;
        }
        
        // 1. 发放任务奖励给任务提交者
        if (recordReward(username, taskReward, 1, null)) {
            Log.d(TAG, "发放任务奖励: 用户=" + username + ", 金额=" + taskReward);
        } else {
            Log.e(TAG, "发放任务奖励失败: 用户=" + username);
        }
        
        // 2. 查找任务提交者的上级推荐人（上游关系链）
        // 获取直接推荐人（1级上游）
        String directInviter = getDirectInviter(username);
        if (directInviter != null) {
            // 检查是否有特权设置
            UserRewardPrivilege privilege = getUserRewardPrivilege(directInviter);
            // 使用特权设置或默认值
            double level1Ratio = privilege != null ? privilege.getLevel1Ratio() : DEFAULT_LEVEL1_RATIO;
            // 计算并发放1级分成奖励
            double level1Reward = taskReward * (level1Ratio / 100.0);
            if (level1Reward > 0 && recordReward(directInviter, level1Reward, 2, username)) {
                Log.d(TAG, "发放1级推荐奖励: 用户=" + directInviter + ", 金额=" + level1Reward);
            }
            
            // 获取二级上游（直接推荐人的推荐人）
            String level2Inviter = getDirectInviter(directInviter);
            if (level2Inviter != null) {
                // 检查是否有特权设置
                UserRewardPrivilege privilege2 = getUserRewardPrivilege(level2Inviter);
                // 使用特权设置或默认值
                double level2Ratio = privilege2 != null ? privilege2.getLevel2Ratio() : DEFAULT_LEVEL2_RATIO;
                // 计算并发放2级分成奖励
                double level2Reward = taskReward * (level2Ratio / 100.0);
                if (level2Reward > 0 && recordReward(level2Inviter, level2Reward, 3, username)) {
                    Log.d(TAG, "发放2级推荐奖励: 用户=" + level2Inviter + ", 金额=" + level2Reward);
                }
                
                // 获取三级上游（二级推荐人的推荐人）
                String level3Inviter = getDirectInviter(level2Inviter);
                if (level3Inviter != null) {
                    // 检查是否有特权设置
                    UserRewardPrivilege privilege3 = getUserRewardPrivilege(level3Inviter);
                    // 使用特权设置或默认值
                    double level3Ratio = privilege3 != null ? privilege3.getLevel3Ratio() : DEFAULT_LEVEL3_RATIO;
                    // 计算并发放3级分成奖励
                    double level3Reward = taskReward * (level3Ratio / 100.0);
                    if (level3Reward > 0 && recordReward(level3Inviter, level3Reward, 4, username)) {
                        Log.d(TAG, "发放3级推荐奖励: 用户=" + level3Inviter + ", 金额=" + level3Reward);
                    }
                }
            }
        }
        
        return true;
    }
    
    // 拒绝任务
    public static boolean rejectTask(int taskId, String reason) {
        Task task = getTaskById(taskId);
        if (task != null) {
            task.setStatus(Task.STATUS_REJECTED);
            task.setRejectionReason(reason);
            return true;
        }
        return false;
    }

    // 获取所有奖励任务
    public static List<RewardTask> getAllRewardTasks() {
        // 从现有的rewardTasks集合中获取所有悬赏任务
        return new ArrayList<>(rewardTasks);
    }
    
    // 根据ID获取奖励任务
    public static RewardTask getRewardTaskById(int taskId) {
        for (RewardTask task : rewardTasks) {
            if (task.getId() == taskId) {
                return task;
            }
        }
        return null;
    }
    
    // 领取奖励任务
    public static boolean takeRewardTask(String username, int taskId) {
        // 查找对应的悬赏任务
        RewardTask targetTask = null;
        for (RewardTask task : rewardTasks) {
            if (task.getId() == taskId) {
                targetTask = task;
                break;
            }
        }
        
        // 如果任务不存在或已被接取，返回失败
        if (targetTask == null || targetTask.isTaken() || targetTask.getRemainingOrders() <= 0) {
            return false;
        }
        
        // 更新任务状态
        targetTask.setRemainingOrders(targetTask.getRemainingOrders() - 1);
        
        // 记录用户接取信息 (这里简化处理，实际应用中应该有更复杂的数据结构)
        targetTask.setTaken(true);
        
        // 用户余额增加
        double reward = targetTask.getReward();
        updateUserBalance(username, reward);
        
        return true;
    }
    
    // 获取用户数据
    public UserData getUserData(String username) {
        // 如果是test_user，返回user1的数据
        if ("test_user".equals(username)) {
            return userDataMap.get(DEFAULT_TEST_USER);
        }
        
        return userDataMap.get(username);
    }
    
    // 获取用户角色
    public String getUserRole(String username) {
        // 如果是test_user，返回普通用户角色
        if ("test_user".equals(username)) {
            return "user";
        }
        
        return userRoles.getOrDefault(username, "user");
    }
    
    // 获取用户角色（非静态版本）
    public String getUserRoleNonStatic(String username) {
        return getUserRole(username);
    }
    
    // 添加新的奖励任务
    public static boolean addRewardTask(RewardTask task) {
        int maxId = 0;
        for (RewardTask t : rewardTasks) {
            if (t.getId() > maxId) {
                maxId = t.getId();
            }
        }
        task.setId(maxId + 1);
        
        rewardTasks.add(task);
        return true;
    }
    
    // 获取所有用户数据（静态方法版本）
    public static List<UserData> getAllUsers() {
        return new ArrayList<>(userDataMap.values());
    }
    
    // 获取所有用户（非静态版本）
    public List<UserData> getAllUsersList() {
        return getAllUsers();
    }
    
    // 更新用户信息
    public static boolean updateUser(UserData userData) {
        if (userDataMap.containsKey(userData.getUsername())) {
            userDataMap.put(userData.getUsername(), userData);
            return true;
        }
        return false;
    }
    
    // 删除用户
    public static boolean deleteUser(String username) {
        if (userDataMap.containsKey(username)) {
            userDataMap.remove(username);
            userRoles.remove(username);
            return true;
        }
        return false;
    }
    
    // 查找用户
    public static UserInfo findUserByUsername(String username) {
        UserData userData = userDataMap.get(username);
        if (userData == null) {
            return null;
        }
        
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(userData.getUsername());
        userInfo.setNickname(userData.getNickname());
        userInfo.setAdmin("admin".equals(userRoles.get(username)));
        return userInfo;
    }
    
    // 添加新用户
    public static boolean addUser(UserData userData, String role) {
        if (!userDataMap.containsKey(userData.getUsername())) {
            userDataMap.put(userData.getUsername(), userData);
            userRoles.put(userData.getUsername(), role);
            return true;
        }
        return false;
    }
    
    /**
     * 获取所有广告列表
     * @return 广告列表
     */
    public static List<Advertisement> getAdvertisements() {
        Log.d(TAG, "Getting advertisements, count: " + advertisements.size());
        for (Advertisement ad : advertisements) {
            Log.d(TAG, "Ad " + ad.getId() + " image URL: " + ad.getImageUrl());
        }
        return new ArrayList<>(advertisements);
    }

    // 获取所有广告
    public List<Advertisement> getAllAdvertisements() {
        return getAdvertisements();
    }
    
    // 获取广告详情
    public static Advertisement getAdvertisementById(int adId) {
        for (Advertisement ad : advertisements) {
            if (ad.getId() == adId) {
                return ad;
            }
        }
        return null;
    }
    
    /**
     * 添加广告
     * @param advertisement 广告对象
     * @return 是否添加成功
     */
    public static boolean addAdvertisement(Advertisement advertisement) {
        Log.d(TAG, "Adding advertisement with image URL: " + advertisement.getImageUrl());
        if (advertisement != null) {
            advertisements.add(advertisement);
            return true;
        }
        return false;
    }
    
    /**
     * 更新广告
     * @param advertisement 广告对象
     * @return 是否更新成功
     */
    public static boolean updateAdvertisement(Advertisement advertisement) {
        Log.d(TAG, "Updating advertisement " + advertisement.getId() + " with image URL: " + advertisement.getImageUrl());
        if (advertisement != null) {
            for (int i = 0; i < advertisements.size(); i++) {
                if (advertisements.get(i).getId() == advertisement.getId()) {
                    advertisements.set(i, advertisement);
                    return true;
                }
            }
        }
        return false;
    }
    
    /**
     * 删除广告
     * @param id 广告ID
     * @return 是否删除成功
     */
    public static boolean deleteAdvertisement(int id) {
        try {
            Iterator<Advertisement> iterator = advertisements.iterator();
            while (iterator.hasNext()) {
                Advertisement ad = iterator.next();
                if (ad.getId() == id) {
                    iterator.remove();
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, "删除广告失败: " + e.getMessage());
            return false;
        }
    }
    
    // 获取所有公告
    public static List<Announcement> getAllAnnouncements() {
        return new ArrayList<>(announcements);
    }
    
    // 获取公告详情
    public static Announcement getAnnouncementById(int id) {
        for (Announcement announcement : announcements) {
            if (announcement.getId() == id) {
                return announcement;
            }
        }
        return null;
    }
    
    // 添加公告
    public static boolean addAnnouncement(Announcement announcement) {
        if (announcement != null) {
            int maxId = 0;
            for (Announcement a : announcements) {
                if (a.getId() > maxId) {
                    maxId = a.getId();
                }
            }
            announcement.setId(maxId + 1);
            announcements.add(announcement);
            return true;
        }
        return false;
    }
    
    // 更新公告
    public static boolean updateAnnouncement(Announcement announcement) {
        if (announcement != null && announcement.getId() > 0) {
            for (int i = 0; i < announcements.size(); i++) {
                if (announcements.get(i).getId() == announcement.getId()) {
                    announcements.set(i, announcement);
                    return true;
                }
            }
        }
        return false;
    }
    
    // 删除公告
    public static boolean deleteAnnouncement(int id) {
        for (int i = 0; i < announcements.size(); i++) {
            if (announcements.get(i).getId() == id) {
                announcements.remove(i);
                return true;
            }
        }
        return false;
    }
    
    /**
     * 获取所有项目列表
     * @return 项目列表
     */
    public static List<Project> getProjects() {
        return new ArrayList<>(projects);
    }
    
    // 兼容方法
    public List<Project> getAllProjects() {
        return getProjects();
    }
    
    // 获取项目详情
    public static Project getProjectById(int id) {
        for (Project project : projects) {
            if (project.getId() == id) {
                return project;
            }
        }
        return null;
    }
    
    /**
     * 添加项目
     * @param project 项目对象
     * @return 是否添加成功
     */
    public static boolean addProject(Project project) {
        try {
            projects.add(project);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "添加项目失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 更新项目
     * @param project 项目对象
     * @return 是否更新成功
     */
    public static boolean updateProject(Project project) {
        try {
            for (int i = 0; i < projects.size(); i++) {
                if (projects.get(i).getId() == project.getId()) {
                    projects.set(i, project);
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, "更新项目失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 删除项目
     * @param id 项目ID
     * @return 是否删除成功
     */
    public static boolean deleteProject(int id) {
        try {
            Iterator<Project> iterator = projects.iterator();
            while (iterator.hasNext()) {
                Project project = iterator.next();
                if (project.getId() == id) {
                    iterator.remove();
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, "删除项目失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 获取用户的悬赏任务列表
     * @param username 用户名
     * @return 用户的悬赏任务列表
     */
    public static List<RewardTask> getUserRewardTasks(String username) {
        List<RewardTask> userTasks = new ArrayList<>();
        for (RewardTask task : rewardTasks) {
            if (username.equals(task.getUsername()) && task.isTaken()) {
                userTasks.add(task);
            }
        }
        return userTasks;
    }
    
    /**
     * 获取用户提交的所有任务（包括待审核、已通过、已拒绝）
     * @param username 用户名
     * @return 用户提交的任务列表
     */
    public static List<Task> getUserTasks(String username) {
        List<Task> userTasks = new ArrayList<>();
        for (Task task : pendingTasks) {
            if (username != null && username.equals(task.getUsername())) {
                userTasks.add(task);
            }
        }
        return userTasks;
    }
    
    // 申请项目
    public static boolean applyForProject(int projectId, int userId) {
        // 在实际应用中，这里需要创建项目申请记录
        // 这里简化处理，仅返回成功
        return true;
    }
    
    // 添加额外兼容方法
    public boolean updateRewardTask(RewardTask task) {
        for (int i = 0; i < rewardTasks.size(); i++) {
            if (rewardTasks.get(i).getId() == task.getId()) {
                rewardTasks.set(i, task);
                return true;
            }
        }
        return false;
    }
    
    public boolean deleteRewardTask(int taskId) {
        for (int i = 0; i < rewardTasks.size(); i++) {
            if (rewardTasks.get(i).getId() == taskId) {
                rewardTasks.remove(i);
                return true;
            }
        }
        return false;
    }

    /**
     * 获取模拟用户列表
     */
    public List<UserInfo> getMockUsers() {
        List<UserInfo> userInfoList = new ArrayList<>();
        for (UserData userData : getAllUsers()) {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userData.getId());
            userInfo.setUsername(userData.getUsername());
            userInfo.setNickname(userData.getNickname());
            userInfo.setPhone(userData.getPhone());
            userInfo.setBalance(String.valueOf(userData.getBalance()));
            userInfo.setPoints(userData.getPoints());
            userInfo.setLevel(userData.getLevel() != null ? userData.getLevel() : "普通");
            userInfo.setStatus("normal");
            userInfoList.add(userInfo);
        }
        return userInfoList;
    }

    /**
     * 更新用户信息
     */
    public boolean updateUser(UserInfo userInfo) {
        for (UserData userData : getAllUsers()) {
            if (userData.getId() == userInfo.getId()) {
                // 更新用户信息
                userData.setUsername(userInfo.getUsername());
                userData.setNickname(userInfo.getNickname());
                userData.setPhone(userInfo.getPhone());
                userData.setLevel(userInfo.getLevel());
                try {
                    userData.setBalance(Double.parseDouble(userInfo.getBalance()));
                } catch (NumberFormatException e) {
                    userData.setBalance(0.0);
                }
                userData.setPoints(userInfo.getPoints());
                // 保存到文件或其他持久化存储
                saveUserData();
                return true;
            }
        }
        return false;
    }

    /**
     * 保存用户数据到持久化存储
     */
    private void saveUserData() {
        // 实际应用中会实现将数据保存到文件或数据库的逻辑
        // 这里仅作为示例，不实际保存
        Log.d(TAG, "保存用户数据到持久化存储");
    }

    /**
     * 获取所有用户特权奖励设置
     * @return 用户特权奖励设置列表
     */
    public static List<UserRewardPrivilege> getUserRewardPrivileges() {
        return new ArrayList<>(userRewardPrivileges);
    }
    
    /**
     * 获取特定用户的特权奖励设置
     * @param username 用户名
     * @return 用户特权奖励设置，若无则返回null
     */
    public static UserRewardPrivilege getUserRewardPrivilege(String username) {
        for (UserRewardPrivilege privilege : userRewardPrivileges) {
            if (privilege.getUsername().equals(username) && privilege.isValid()) {
                return privilege;
            }
        }
        return null;
    }
    
    /**
     * 添加用户特权奖励设置
     * @param privilege 用户特权奖励设置
     * @return 是否添加成功
     */
    public static boolean addUserRewardPrivilege(UserRewardPrivilege privilege) {
        if (privilege == null) {
            return false;
        }
        
        // 设置ID
        int maxId = 0;
        for (UserRewardPrivilege p : userRewardPrivileges) {
            if (p.getId() > maxId) {
                maxId = p.getId();
            }
        }
        privilege.setId(maxId + 1);
        
        // 添加到集合
        userRewardPrivileges.add(privilege);
        return true;
    }
    
    /**
     * 更新用户特权奖励设置
     * @param privilege 用户特权奖励设置
     * @return 是否更新成功
     */
    public static boolean updateUserRewardPrivilege(UserRewardPrivilege privilege) {
        if (privilege == null || privilege.getId() <= 0) {
            return false;
        }
        
        for (int i = 0; i < userRewardPrivileges.size(); i++) {
            if (userRewardPrivileges.get(i).getId() == privilege.getId()) {
                userRewardPrivileges.set(i, privilege);
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * 删除用户特权奖励设置
     * @param id 特权ID
     * @return 是否删除成功
     */
    public static boolean deleteUserRewardPrivilege(int id) {
        for (int i = 0; i < userRewardPrivileges.size(); i++) {
            if (userRewardPrivileges.get(i).getId() == id) {
                userRewardPrivileges.remove(i);
                return true;
            }
        }
        
        return false;
    }

    /**
     * 获取特权用户列表
     * @return 特权用户列表
     */
    public static List<UserInfo> getPrivilegeUsers() {
        List<UserInfo> privilegeUsers = new ArrayList<>();
        
        // 创建一些模拟的特权用户
        UserInfo user1 = new UserInfo();
        user1.setId(101);
        user1.setUsername("特权用户1");
        user1.setNickname("VIP用户1");
        user1.setLevel("钻石");
        
        UserInfo user2 = new UserInfo();
        user2.setId(102);
        user2.setUsername("特权用户2");
        user2.setNickname("VIP用户2");
        user2.setLevel("白金");
        
        UserInfo user3 = new UserInfo();
        user3.setId(103);
        user3.setUsername("特权用户3");
        user3.setNickname("VIP用户3");
        user3.setLevel("黄金");
        
        privilegeUsers.add(user1);
        privilegeUsers.add(user2);
        privilegeUsers.add(user3);
        
        return privilegeUsers;
    }

    /**
     * 根据ID查找用户
     * @param userId 用户ID
     * @return 用户信息，未找到则返回null
     */
    public UserInfo getUserById(int userId) {
        // 先从静态方法获取所有用户数据
        List<UserData> allUsers = getAllUsers();
        for (UserData userData : allUsers) {
            if (userData.getId() == userId) {
                // 将UserData转换为UserInfo
                UserInfo userInfo = new UserInfo();
                userInfo.setId(userData.getId());
                userInfo.setUsername(userData.getUsername());
                userInfo.setNickname(userData.getNickname());
                userInfo.setPhone(userData.getPhone());
                userInfo.setBalance(String.valueOf(userData.getBalance()));
                userInfo.setPoints(userData.getPoints());
                userInfo.setLevel(userData.getLevel() != null ? userData.getLevel() : "普通");
                userInfo.setStatus("normal");
                return userInfo;
            }
        }

        // 如果没有找到匹配的用户，尝试从测试用户中查找
        List<UserInfo> testUsers = getMockUsers();
        for (UserInfo userInfo : testUsers) {
            if (userInfo.getId() == userId) {
                return userInfo;
            }
        }

        return null;
    }

    // 静态获取用户角色的代理方法
    public static String getUserRoleStatic(String username) {
        return getInstance().getUserRole(username);
    }
    
    // 静态获取用户数据的代理方法
    public static UserData getUserDataStatic(String username) {
        return getInstance().getUserData(username);
    }

    /**
     * 用户创建新任务
     * @param title 任务标题
     * @param description 任务描述
     * @param reward 奖励金额
     * @param username 创建者用户名
     * @return 创建是否成功
     */
    public boolean createNewTask(String title, String description, float reward, String username) {
        try {
            // 获取用户数据
            UserData userData = userDataMap.get(username);
            if (userData == null) {
                Log.e(TAG, "创建任务失败：找不到用户 " + username);
                return false;
            }
            
            // 检查用户余额是否足够
            if (userData.getBalance() < reward) {
                Log.e(TAG, "创建任务失败：用户 " + username + " 余额不足");
                return false;
            }
            
            // 扣除用户余额
            userData.setBalance(userData.getBalance() - reward);
            
            // 生成新任务ID
            int newId = 1;
            if (!rewardTasks.isEmpty()) {
                for (RewardTask task : rewardTasks) {
                    if (task.getId() >= newId) {
                        newId = task.getId() + 1;
                    }
                }
            }
            
            // 创建一个新任务
            RewardTask newTask = new RewardTask();
            newTask.setId(newId);
            newTask.setTitle(title);
            newTask.setDescription(description);
            newTask.setReward(reward);
            newTask.setStatus("pending");
            newTask.setUsername(username); // 使用username代替setCreator
            newTask.setCreatedAt(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); // 日期格式化为字符串
            
            // 设置默认的订单数量
            newTask.setTotalOrders(5);
            newTask.setRemainingOrders(5);
            newTask.setTaken(false);
            
            // 添加到奖励任务列表
            rewardTasks.add(newTask);
            
            // 同时添加到待审核任务列表
            Task pendingTask = new Task();
            pendingTask.setId(newId);
            pendingTask.setTitle(title);
            pendingTask.setDescription(description);
            pendingTask.setReward(reward);
            pendingTask.setStatus(Task.STATUS_PENDING);
            pendingTask.setUsername(username);
            pendingTask.setSubmittedAt(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            
            // 添加到待审核任务列表
            pendingTasks.add(pendingTask);
            
            Log.d(TAG, "成功创建新任务：ID=" + newId + ", 标题=" + title);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "创建任务时发生异常", e);
            return false;
        }
    }

    /**
     * 检查用户是否已解锁特定项目
     * @param username 用户名
     * @param projectId 项目ID
     * @return 是否已解锁
     */
    public static boolean hasUnlockedProject(String username, int projectId) {
        for (ProjectUnlockStatus status : projectUnlockStatuses) {
            if (status.getUsername().equals(username) && status.getProjectId() == projectId) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 用户解锁项目
     * @param username 用户名
     * @param projectId 项目ID
     * @param unlockPrice 解锁价格
     * @return 是否解锁成功
     */
    public static boolean unlockProject(String username, int projectId, double unlockPrice) {
        // 检查是否已经解锁
        if (hasUnlockedProject(username, projectId)) {
            return true; // 已经解锁过，直接返回成功
        }
        
        // 检查用户余额是否足够
        UserData userData = getInstance().getUserData(username);
        if (userData == null) {
            Log.e(TAG, "解锁项目失败：找不到用户 " + username);
            return false;
        }
        
        if (userData.getBalance() < unlockPrice) {
            Log.e(TAG, "解锁项目失败：用户 " + username + " 余额不足");
            return false;
        }
        
        // 扣除用户余额
        userData.setBalance(userData.getBalance() - unlockPrice);
        
        // 创建解锁记录
        int newId = projectUnlockStatuses.size() + 1;
        ProjectUnlockStatus status = new ProjectUnlockStatus(
            newId, 
            projectId, 
            username, 
            new Date(), 
            unlockPrice
        );
        projectUnlockStatuses.add(status);
        
        return true;
    }
    
    /**
     * 获取用户所有已解锁的项目ID列表
     * @param username 用户名
     * @return 已解锁的项目ID列表
     */
    public static List<Integer> getUserUnlockedProjectIds(String username) {
        List<Integer> unlockedIds = new ArrayList<>();
        for (ProjectUnlockStatus status : projectUnlockStatuses) {
            if (status.getUsername().equals(username)) {
                unlockedIds.add(status.getProjectId());
            }
        }
        return unlockedIds;
    }
    
    /**
     * 获取用户的已解锁项目列表
     * @param username 用户名
     * @return
     */
    public static List<Project> getUserUnlockedProjects(String username) {
        List<Project> unlockedProjects = new ArrayList<>();
        List<Integer> unlockedIds = getUserUnlockedProjectIds(username);
        
        for (Project project : projects) {
            if (unlockedIds.contains(project.getId())) {
                unlockedProjects.add(project);
            }
        }
        
        return unlockedProjects;
    }

    /**
     * 获取用户的直接推荐人
     * @param username 用户名
     * @return 推荐人用户名，如果没有则返回null
     */
    public static String getDirectInviter(String username) {
        UserData userData = userDataMap.get(username);
        if (userData != null) {
            return userData.getInviter();
        }
        return null;
    }

    /**
     * 获取用户的推荐人链，最多返回3级
     * @param username 用户名
     * @return 包含用户推荐人链的列表，按照一级、二级、三级顺序排列
     */
    public static List<String> getInviterChain(String username) {
        List<String> inviterChain = new ArrayList<>();
        
        // 获取一级推荐人
        String level1Inviter = getDirectInviter(username);
        if (level1Inviter != null) {
            inviterChain.add(level1Inviter);
            
            // 获取二级推荐人
            String level2Inviter = getDirectInviter(level1Inviter);
            if (level2Inviter != null) {
                inviterChain.add(level2Inviter);
                
                // 获取三级推荐人
                String level3Inviter = getDirectInviter(level2Inviter);
                if (level3Inviter != null) {
                    inviterChain.add(level3Inviter);
                }
            }
        }
        
        return inviterChain;
    }

    /**
     * 记录用户奖励
     * @param username 用户名
     * @param amount 奖励金额
     * @param type 奖励类型 (1-任务直接奖励, 2-一级推荐, 3-二级推荐, 4-三级推荐)
     * @param sourceUsername 来源用户
     * @return 是否记录成功
     */
    public static boolean recordReward(String username, double amount, int type, String sourceUsername) {
        if (username == null || username.isEmpty() || amount <= 0) {
            return false;
        }
        
        UserData userData = userDataMap.get(username);
        if (userData == null) {
            return false;
        }
        
        // 增加用户余额
        userData.setBalance(userData.getBalance() + amount);
        
        // 根据类型记录今日收入
        switch (type) {
            case 1: // 任务直接奖励
                userData.setTaskRewardToday(userData.getTaskRewardToday() + amount);
                break;
            case 2: // 一级推荐
            case 3: // 二级推荐
            case 4: // 三级推荐
                userData.setSubTaskReward(userData.getSubTaskReward() + amount);
                break;
            default:
                // 其他类型不记录到指定统计中
                break;
        }
        
        // 这里可以添加记录奖励明细的代码
        Log.d(TAG, "记录用户奖励: 用户=" + username + ", 金额=" + amount + 
              ", 类型=" + type + ", 来源=" + sourceUsername);
        
        return true;
    }

    /**
     * 更新用户头像URL
     * @param username 用户名
     * @param avatarUrl 头像URL
     * @return 是否更新成功
     */
    public boolean updateUserAvatar(String username, String avatarUrl) {
        UserData userData = userDataMap.get(username);
        if (userData != null) {
            userData.setAvatarUrl(avatarUrl);
            userDataMap.put(username, userData);
            return true;
        }
        return false;
    }
    
    /**
     * 获取用户头像URL
     * @param username 用户名
     * @return 头像URL，如果不存在返回null
     */
    public String getUserAvatarUrl(String username) {
        UserData userData = userDataMap.get(username);
        if (userData != null) {
            return userData.getAvatarUrl();
        }
        return null;
    }

    /**
     * 创建提现记录
     * @param username 用户名
     * @param amount 提现金额
     * @param alipayAccount 支付宝账号
     * @param alipayName 支付宝实名
     * @return 成功返回记录ID，失败返回-1
     */
    public int createWithdrawalRecord(String username, double amount, String alipayAccount, String alipayName) {
        // 添加详细日志
        Log.d(TAG, "创建提现记录: 用户名=" + username + 
              ", 金额=" + amount + 
              ", 支付宝账号=" + alipayAccount + 
              ", 支付宝姓名=" + alipayName);
        
        // 验证参数
        if (username == null || amount <= 0 || alipayAccount == null || alipayName == null) {
            Log.e(TAG, "提现记录创建失败: 参数无效");
            return -1;
        }
        
        // 检查用户是否存在
        if (!userDataMap.containsKey(username)) {
            Log.e(TAG, "提现记录创建失败: 用户 " + username + " 不存在于userDataMap中");
            
            // 查看当前userDataMap中的用户
            StringBuilder userList = new StringBuilder("当前存在的用户: ");
            for (String user : userDataMap.keySet()) {
                userList.append(user).append(", ");
            }
            Log.d(TAG, userList.toString());
            
            // 尝试使用test_user作为替代
            if ("test_user".equals(username) && userDataMap.containsKey(DEFAULT_TEST_USER)) {
                username = DEFAULT_TEST_USER;
                Log.d(TAG, "使用默认测试用户 " + DEFAULT_TEST_USER + " 替代 test_user");
            } else {
                return -1;
            }
        }
        
        // 检查用户余额是否足够
        UserData userData = userDataMap.get(username);
        if (userData == null) {
            Log.e(TAG, "提现记录创建失败: 无法获取用户数据");
            return -1;
        }
        
        Log.d(TAG, "用户 " + username + " 当前余额: " + userData.getBalance());
        
        if (userData.getBalance() < amount) {
            Log.e(TAG, "提现记录创建失败: 余额不足 (余额=" + userData.getBalance() + ", 提现金额=" + amount + ")");
            return -1;
        }
        
        // 创建提现记录
        WithdrawalRecord record = new WithdrawalRecord(username, amount, alipayAccount, alipayName);
        record.setId(nextWithdrawalId++);
        withdrawalRecords.add(record);
        
        Log.d(TAG, "提现记录创建成功: ID=" + record.getId());
        
        return record.getId();
    }
    
    /**
     * 获取用户的提现记录列表
     * @param username 用户名
     * @return 该用户的提现记录列表
     */
    public List<WithdrawalRecord> getUserWithdrawalRecords(String username) {
        List<WithdrawalRecord> userRecords = new ArrayList<>();
        for (WithdrawalRecord record : withdrawalRecords) {
            if (record.getUsername().equals(username)) {
                userRecords.add(record);
            }
        }
        return userRecords;
    }
    
    /**
     * 获取所有提现记录（管理员用）
     * @return 所有提现记录
     */
    public List<WithdrawalRecord> getAllWithdrawalRecords() {
        return new ArrayList<>(withdrawalRecords);
    }
    
    /**
     * 获取指定状态的提现记录（管理员用）
     * @param status 状态值
     * @return 符合状态的提现记录
     */
    public List<WithdrawalRecord> getWithdrawalRecordsByStatus(String status) {
        List<WithdrawalRecord> filteredRecords = new ArrayList<>();
        for (WithdrawalRecord record : withdrawalRecords) {
            if (record.getStatus().equals(status)) {
                filteredRecords.add(record);
            }
        }
        return filteredRecords;
    }
    
    /**
     * 通过ID获取提现记录
     * @param id 记录ID
     * @return 提现记录，不存在返回null
     */
    public WithdrawalRecord getWithdrawalRecordById(int id) {
        for (WithdrawalRecord record : withdrawalRecords) {
            if (record.getId() == id) {
                return record;
            }
        }
        return null;
    }
    
    /**
     * 审核提现申请（管理员用）
     * @param id 提现记录ID
     * @param approved 是否通过
     * @param remarks 备注（拒绝原因等）
     * @return 是否操作成功
     */
    public boolean processWithdrawalRecord(int id, boolean approved, String remarks) {
        WithdrawalRecord record = getWithdrawalRecordById(id);
        if (record == null || !record.getStatus().equals(WithdrawalRecord.STATUS_PENDING)) {
            return false;
        }
        
        // 更新状态和处理时间
        record.setProcessTime(new Date());
        record.setRemarks(remarks);
        
        if (approved) {
            // 通过申请，扣减用户余额
            record.setStatus(WithdrawalRecord.STATUS_APPROVED);
            UserData userData = userDataMap.get(record.getUsername());
            if (userData != null) {
                userData.setBalance(userData.getBalance() - record.getAmount());
                userDataMap.put(record.getUsername(), userData);
            }
        } else {
            // 拒绝申请，不扣减余额
            record.setStatus(WithdrawalRecord.STATUS_REJECTED);
        }
        
        return true;
    }
    
    /**
     * 获取用户的提现余额上限
     * @param username 用户名
     * @return 可提现的余额上限
     */
    public double getUserWithdrawalLimit(String username) {
        UserData userData = userDataMap.get(username);
        if (userData == null) {
            return 0.0;
        }
        return userData.getBalance();
    }

    /**
     * 获取用户上传任务被完成的记录
     * @param username 用户名
     * @return 用户上传任务被完成的记录列表
     */
    public List<TaskRecord> getUserPostedCompletedTasks(String username) {
        // 模拟数据 - 实际应用中应从数据库查询
        List<TaskRecord> records = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String today = sdf.format(new Date());
        
        // 添加示例记录
        TaskRecord record1 = new TaskRecord();
        record1.setId(101);
        record1.setTaskName("网站用户体验测试");
        record1.setUsername("user_other1"); // 完成任务的用户
        record1.setTaskDescription("这是用户" + username + "发布的任务，由其他用户完成");
        record1.setStatus(TaskRecord.STATUS_APPROVED); // 已通过
        record1.setReward(20.0);
        record1.setCompletionTime(today);
        record1.setApprovalTime(today);
        record1.setRemark("用户上传任务");
        records.add(record1);
        
        TaskRecord record2 = new TaskRecord();
        record2.setId(102);
        record2.setTaskName("APP功能测试");
        record2.setUsername("user_other2"); // 完成任务的用户
        record2.setTaskDescription("这是用户" + username + "发布的任务，由其他用户完成");
        record2.setStatus(TaskRecord.STATUS_APPROVED); // 已通过
        record2.setReward(15.0);
        record2.setCompletionTime(today);
        record2.setApprovalTime(today);
        record2.setRemark("用户上传任务");
        records.add(record2);
        
        return records;
    }

    /**
     * 更新用户余额
     * @param username 用户名
     * @param amount 增加的余额金额
     * @return 是否更新成功
     */
    private static boolean updateUserBalance(String username, double amount) {
        UserData userData = userDataMap.get(username);
        if (userData == null) {
            return false;
        }
        
        userData.setBalance(userData.getBalance() + amount);
        return true;
    }

    /**
     * 获取用户接取的悬赏任务列表
     * @param username 用户名
     * @return 用户接取的悬赏任务列表
     */
    public List<RewardTask> getUserRewardTasks(String username) {
        // 调用静态方法版本，避免代码重复
        return getUserRewardTasks(username);
    }
    
    /**
     * 取消用户接取的悬赏任务
     * @param username 用户名
     * @param taskId 任务ID
     * @return 是否取消成功
     */
    public boolean cancelRewardTask(String username, int taskId) {
        for (RewardTask task : rewardTasks) {
            if (task.getId() == taskId && username.equals(task.getUsername())) {
                // 只有进行中的任务才能取消
                if (task.getProgressStatus() == RewardTask.STATUS_IN_PROGRESS) {
                    // 移除用户关联
                    task.setUsername(null);
                    task.setTaken(false);
                    // 恢复任务剩余数量
                    task.setRemainingOrders(task.getRemainingOrders() + 1);
                    return true;
                }
                break;
            }
        }
        return false;
    }
    
    /**
     * 提交悬赏任务
     * @param taskId 任务ID
     * @param username 用户名
     * @param content 提交内容
     * @return 是否提交成功
     */
    public boolean submitRewardTask(int taskId, String username, String content) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String now = sdf.format(new Date());
        
        for (RewardTask task : rewardTasks) {
            if (task.getId() == taskId && username.equals(task.getUsername())) {
                // 只有进行中的任务才能提交
                if (task.getProgressStatus() == RewardTask.STATUS_IN_PROGRESS) {
                    task.setProgressStatus(RewardTask.STATUS_UNDER_REVIEW);
                    task.setSubmissionContent(content);
                    task.setSubmissionTime(now);
                    return true;
                }
                break;
            }
        }
        return false;
    }
    
    /**
     * 审核悬赏任务
     * @param taskId 任务ID
     * @param approved 是否通过
     * @param comment 评语
     * @return 是否审核成功
     */
    public boolean reviewRewardTask(int taskId, boolean approved, String comment) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String now = sdf.format(new Date());
        
        for (RewardTask task : rewardTasks) {
            if (task.getId() == taskId) {
                // 只有审核中的任务才能审核
                if (task.getProgressStatus() == RewardTask.STATUS_UNDER_REVIEW) {
                    // 设置审核状态
                    task.setProgressStatus(approved ? RewardTask.STATUS_COMPLETED : RewardTask.STATUS_REJECTED);
                    task.setReviewComment(comment);
                    task.setReviewTime(now);
                    
                    // 如果通过，发放奖励
                    if (approved) {
                        String username = task.getUsername();
                        double reward = task.getReward();
                        updateUserBalance(username, reward);
                    }
                    
                    return true;
                }
                break;
            }
        }
        return false;
    }
    
    /**
     * 获取所有待审核的悬赏任务
     * @return 待审核的悬赏任务列表
     */
    public List<RewardTask> getPendingReviewRewardTasks() {
        List<RewardTask> pendingTasks = new ArrayList<>();
        for (RewardTask task : rewardTasks) {
            if (task.getProgressStatus() == RewardTask.STATUS_UNDER_REVIEW) {
                pendingTasks.add(task);
            }
        }
        
        // 如果没有待审核任务，添加一些测试数据
        if (pendingTasks.isEmpty()) {
            // 添加测试数据
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String now = sdf.format(new Date());
            
            // 待审核任务1
            RewardTask task1 = new RewardTask();
            task1.setId(20001);
            task1.setTitle("网站Bug测试");
            task1.setDescription("测试网站的各项功能，找出并报告所有Bug");
            task1.setReward(25.0);
            task1.setUsername("test_user1");
            task1.setCreatedAt(sdf.format(new Date(System.currentTimeMillis() - 86400000 * 2))); // 2天前
            task1.setDeadline(sdf.format(new Date(System.currentTimeMillis() + 86400000))); // 1天后
            task1.setProgressStatus(RewardTask.STATUS_UNDER_REVIEW);
            task1.setSubmissionContent("已完成网站测试，共发现3个Bug：1. 登录验证码错误；2. 购物车结算异常；3. 个人中心无法修改头像");
            task1.setSubmissionTime(sdf.format(new Date(System.currentTimeMillis() - 86400000))); // 1天前
            pendingTasks.add(task1);
            
            // 待审核任务2
            RewardTask task2 = new RewardTask();
            task2.setId(20002);
            task2.setTitle("APP使用体验评测");
            task2.setDescription("体验APP的各项功能，并提交一份使用体验报告");
            task2.setReward(30.0);
            task2.setUsername("test_user2");
            task2.setCreatedAt(sdf.format(new Date(System.currentTimeMillis() - 86400000 * 3))); // 3天前
            task2.setDeadline(sdf.format(new Date(System.currentTimeMillis() + 86400000 * 2))); // 2天后
            task2.setProgressStatus(RewardTask.STATUS_UNDER_REVIEW);
            task2.setSubmissionContent("已完成APP体验评测，提交了详细的优缺点分析和改进建议");
            task2.setSubmissionTime(sdf.format(new Date(System.currentTimeMillis() - (long)(86400000 * 1.5)))); // 1.5天前
            pendingTasks.add(task2);
        }
        
        return pendingTasks;
    }
    
    // 删除重复方法
    // /**
    //  * 根据ID获取悬赏任务
    //  * @param taskId 任务ID
    //  * @return 悬赏任务对象，如果找不到则返回null
    //  */
    // public RewardTask getRewardTaskById(int taskId) {
    //     for (RewardTask task : rewardTasks) {
    //         if (task.getId() == taskId) {
    //             return task;
    //         }
    //     }
    //     return null;
    // }

    /**
     * 根据ID获取悬赏任务
     * @param taskId 任务ID
     * @return 悬赏任务对象，如果找不到则返回null
     */
    public RewardTask getRewardTaskById(int taskId) {
        // 调用静态方法版本，避免代码重复
        return getRewardTaskById(taskId);
    }
} 